package com.logistics.service.impl;

import com.logistics.common.Result;
import com.logistics.entity.Warehouse;
import com.logistics.mapper.WarehouseMapper;
import com.logistics.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class WarehouseServiceImpl implements WarehouseService {
    @Autowired
    private WarehouseMapper warehouseMapper;

    @Override
    @Transactional
    public Result<Warehouse> create(Warehouse warehouse) {
        warehouse.setUsedCapacity(BigDecimal.ZERO);
        warehouse.setStatus(String.valueOf(1));
        warehouseMapper.insert(warehouse);
        return Result.success(warehouse);
    }

    @Override
    public Result<Warehouse> getById(Long id) {
        Warehouse warehouse = warehouseMapper.selectById(id);
        return Result.success(warehouse);
    }

    @Override
    public Result<Warehouse> getByName(String name) {
        Warehouse warehouse = warehouseMapper.selectByName(name);
        return Result.success(warehouse);
    }

    @Override
    public Result<List<Warehouse>> list() {
        List<Warehouse> warehouses = warehouseMapper.selectAll();
        return Result.success(warehouses);
    }

    @Override
    public Result<List<Warehouse>> search(String name, Integer status) {
        List<Warehouse> warehouses = warehouseMapper.search(name, status);
        return Result.success(warehouses);
    }

    @Override
    @Transactional
    public Result<Warehouse> update(Warehouse warehouse) {
        // 检查仓库是否存在
        Warehouse existWarehouse = warehouseMapper.selectById(warehouse.getId());
        if (existWarehouse == null) {
            return Result.error("仓库不存在");
        }
        
        warehouseMapper.update(warehouse);
        return Result.success(warehouse);
    }

    @Override
    @Transactional
    public Result<Void> delete(Long id) {
        // 检查仓库是否存在
        Warehouse warehouse = warehouseMapper.selectById(id);
        if (warehouse == null) {
            return Result.error("仓库不存在");
        }
        
        warehouseMapper.deleteById(id);
        return Result.success();
    }

    @Override
    @Transactional
    public Result<Void> updateUsedCapacity(Long id, BigDecimal usedCapacity) {
        // 检查仓库是否存在
        Warehouse warehouse = warehouseMapper.selectById(id);
        if (warehouse == null) {
            return Result.error("仓库不存在");
        }
        
        // 检查容量是否超出
        if (usedCapacity.compareTo(warehouse.getCapacity()) > 0) {
            return Result.error("已用容量不能超过总容量");
        }
        
        warehouseMapper.updateUsedCapacity(id, usedCapacity);
        return Result.success();
    }

    @Override
    public Result<List<Map<String, Object>>> listWarehouses() {
        return null;
    }
} 